package cat.joronya.supermanager.market;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.SpinnerAdapter;
import android.widget.TabHost;
import android.widget.TabHost.TabContentFactory;
import cat.joronya.supermanager.R;
import cat.joronya.supermanager.Supermanager;
import cat.joronya.supermanager.drawer.DrawerActivity;
import cat.joronya.supermanager.drawer.DrawerItem;
import cat.joronya.supermanager.home.HomeActivity;
import cat.joronya.supermanager.market.MarketListFragment.OnBuyListener;
import cat.joronya.supermanager.market.MarketListFragment.OnFavListener;
import cat.joronya.supermanager.market.MarketListFragment.OnSortListener;
import cat.joronya.supermanager.market.SortDialogFragment.OnSelectedSortCriteriaListener;
import cat.joronya.supermanager.privateleague.PrivateLeagueListActivity;
import cat.joronya.supermanager.team.MyTeamsListActivity;

public class MarketListActivity extends DrawerActivity implements OnFavListener, OnBuyListener, 
	OnSortListener, OnSelectedSortCriteriaListener, TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener,
	ActionBar.OnNavigationListener
{
	// pel Log
	private static final String TAG = "supermanager";
	
	private TabHost mTabHost;
	private ViewPager mViewPager;
    private HashMap<String, TabInfo> mapTabInfo = new HashMap<String, MarketListActivity.TabInfo>();
    private PagerAdapter mPagerAdapter;
    
    private String jornada = "0";
	
    private class TabInfo 
    {
        private String tag;
        private Class<?> clss;
        private Bundle args;
        private Fragment fragment;
        TabInfo(String tag, Class<?> clazz, Bundle args) 
        {
            this.tag = tag;
            this.clss = clazz;
            this.args = args;
        }
    }
    
    public interface OnChangeFilter {
    	public void onChangeFilter(String group);
    }
    
    protected List<OnChangeFilter> mFilterListeners = new ArrayList<OnChangeFilter>();
    
    public void addChangeFilterListener(OnChangeFilter listener)
    {
    	mFilterListeners.add(listener);
    }
    
    public void removeChangeFilterListener(OnChangeFilter listener)
    {
    	mFilterListeners.remove(listener);
    }
    
    class TabFactory implements TabContentFactory 
    {
        private final Context mContext;
 
        /**
         * @param context
         */
        public TabFactory(Context context) {
            mContext = context;
        }
 
        /** (non-Javadoc)
         * @see android.widget.TabHost.TabContentFactory#createTabContent(java.lang.String)
         */
        public View createTabContent(String tag) {
            View v = new View(mContext);
            v.setMinimumWidth(0);
            v.setMinimumHeight(0);
            return v;
        }
    }
    
    public boolean onNavigationItemSelected(int position, long itemId) 
	{
		  Log.d(Supermanager.TAG, "OnNavigationListener.onNavigationItemSelected... position: "+position+", itemId: "+itemId);
		  
		  if( position == 0 )
		  {
			  // cas de mostrar tot
			  mCurrentListName = null;
		  }
		  else if( position == 1 && mFavListName != null )
		  {
			  // sempre posem Favorites al 2on, en cas de tenir-ne
			  mCurrentListName = "fav";
		  }
		  else
		  {
			  // altrament el nom que hagi posat l'usuari
			  mCurrentListName = "kk";
		  }
		  
		  for(OnChangeFilter listener: mFilterListeners)
		  {
			  if( listener != null )
				  listener.onChangeFilter(mCurrentListName);
		  }
		  return true;
	}
    
    private String mFavListName = null;
    private String[] mListNames = null;
    private String mCurrentListName = null;
    
    public String getCurrentListName()
    {
    	return mCurrentListName;
    }
    
    private String[] getPlayerLists(String jornada)
    {
    	ArrayList<String> lists = new ArrayList<String>();
    	
    	// afegim filtre general, sense filtre, al index 0
    	lists.add(getString(R.string.market_tab, jornada));
    	
    	// query to get player list names
    	Cursor listCursor = getContentResolver().query(Supermanager.PlayerList.CONTENT_URI, 
    			new String[]{Supermanager.PlayerList.LIST_NAME}, null, null, null);
    	while( listCursor.moveToNext() )
    	{
    		lists.add(listCursor.getString(0));
    	}
    	
    	// si teniem algun a favoritos, treiem per posar-lo al index 1
    	if( lists.contains(Supermanager.FAV_LISTNAME) )
    	{
    		lists.remove(Supermanager.FAV_LISTNAME);
    		mFavListName = getString(R.string.market_favorites);
    		lists.add(1, mFavListName);
    	}
    	
    	String[] listStrings = new String[lists.size()];
    	listStrings = lists.toArray(listStrings);
    	return listStrings;
    }
    
	/** 
	 * Called when the activity is first created. 
	 */
	@Override
    public void onCreate(Bundle savedInstanceState) 
    {
		// set layout and call super onCreate
    	setmLayoutResource(R.layout.market_drawer_layout);
    	setmLayoutId(R.id.drawer_layout);
    	super.onCreate(savedInstanceState);
    	
    	// tenim params?
    	final String idequ = getIntent().getStringExtra("cat.joronya.supermanager.myteamdetail.idequ");
        final String buyPosition = getIntent().getStringExtra("cat.joronya.supermanager.myteamdetail.position");
    	final String buyCash = getIntent().getStringExtra("cat.joronya.supermanager.myteamdetail.cash");
    	
    	// recuperem la jornada actual
    	getLastDayOfMarket();
        
    	mListNames = getPlayerLists(jornada);
    	
    	SpinnerAdapter mSpinnerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mListNames);
    	
    	getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
		getSupportActionBar().setListNavigationCallbacks(mSpinnerAdapter, this);
    	
    	// Initialise the TabHost
        this.initialiseTabHost(savedInstanceState, buyPosition, buyCash);
        
        // Intialise ViewPager
        this.intialiseViewPager(idequ, buyPosition, buyCash);
        
        // set current saved tab after initialiseViewPager
        if (savedInstanceState != null) {
            mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab")); //set the tab as per the saved state
        }
        
        // titol de la pantalla home inicalment
        //setTitle(getResources().getString(R.string.market_tab, jornada));
        setTitle("");
    }
	
	@Override
	protected void onNewIntent(Intent intent) 
	{
    	// tenim params?
		final String idequ = getIntent().getStringExtra("cat.joronya.supermanager.myteamdetail.idequ");
        final String buyPosition = getIntent().getStringExtra("cat.joronya.supermanager.myteamdetail.position");
    	final String buyCash = getIntent().getStringExtra("cat.joronya.supermanager.myteamdetail.cash");
    	
    	// Initialise the TabHost
        this.initialiseTabHost(new Bundle(), buyPosition, buyCash);

        // Intialise ViewPager
        this.intialiseViewPager(idequ, buyPosition, buyCash);
        
        // titol de la pantalla home inicalment
        getLastDayOfMarket();
        //setTitle(getResources().getString(R.string.market_tab, jornada));    

        super.onNewIntent(intent);
	}
	
	private void getLastDayOfMarket()
	{
		 // recuperem el nom de la lliga i la jornada
		MarketProvider marketProvider = new MarketProvider();
		Cursor daysCursor = marketProvider.getDays(getApplicationContext());
        
		Log.d(TAG,"MarketListActivity.getLastDayOfMarket cursor rows: "+daysCursor.getCount());
		
		// agafem la jornada
        if( daysCursor.moveToLast() )
		{
        	jornada = daysCursor.getString(0);
		}
        
        daysCursor.close();
	}
	
	/** (non-Javadoc)
     * @see android.support.v4.app.FragmentActivity#onSaveInstanceState(android.os.Bundle)
     */
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString("tab", mTabHost.getCurrentTabTag()); //save the tab selected
        super.onSaveInstanceState(outState);
    }
    
    /**
     * Initialise ViewPager
     */
    private void intialiseViewPager(String idequ, String buyPosition, String buyCash) 
    {
        List<Fragment> fragments = new Vector<Fragment>();
        
        // activate the tabs nedded, all or the one in buy process
        if( buyPosition != null && buyPosition.startsWith("b") )
        {
        	fragments.add(MarketListFragment.newInstance(idequ, buyPosition, buyCash, MarketListFragment.POSITION_GUARDS, jornada));
        }
        else if( buyPosition != null && buyPosition.startsWith("a") )
        {
        	fragments.add(MarketListFragment.newInstance(idequ, buyPosition, buyCash, MarketListFragment.POSITION_FORWARDS, jornada));
        }
        else if( buyPosition != null && buyPosition.startsWith("p") )
        {
        	fragments.add(MarketListFragment.newInstance(idequ, buyPosition, buyCash, MarketListFragment.POSITION_CENTERS, jornada));
        }
        else
        {
        	fragments.add(MarketListFragment.newInstance(idequ, buyPosition, buyCash, MarketListFragment.POSITION_GUARDS, jornada));
        	fragments.add(MarketListFragment.newInstance(idequ, buyPosition, buyCash, MarketListFragment.POSITION_FORWARDS, jornada));
        	fragments.add(MarketListFragment.newInstance(idequ, buyPosition, buyCash, MarketListFragment.POSITION_CENTERS, jornada));
        }

        this.mPagerAdapter  = new PagerAdapter(super.getSupportFragmentManager(), fragments);
        //
        this.mViewPager = (ViewPager)super.findViewById(R.id.viewpager);
        this.mViewPager.setAdapter(this.mPagerAdapter);
        this.mViewPager.setOnPageChangeListener(this);
    }
    
    /**
     * Initialise the Tab Host
     */
    private void initialiseTabHost(Bundle args, String buyPosition, String buyCash) 
    {
        mTabHost = (TabHost)findViewById(android.R.id.tabhost);
        mTabHost.setup();
        TabInfo tabInfo = null;
        
        // activate the tabs nedded, all or the one in buy process
        if( buyPosition != null && buyPosition.startsWith("b") )
        {
        	String indicator = getString(R.string.market_menu_guards);
        	MarketListActivity.AddTab(this, 
        			this.mTabHost, 
        			this.mTabHost.newTabSpec("guards").setIndicator(indicator), ( 
        					tabInfo = new TabInfo("guards", MarketListFragment.class, args)));
        	this.mapTabInfo.put(tabInfo.tag, tabInfo);
        }
        else if( buyPosition != null && buyPosition.startsWith("a") )
        {
        	String indicator = getString(R.string.market_menu_forwards);
        	MarketListActivity.AddTab(this, 
        			this.mTabHost, 
        			this.mTabHost.newTabSpec("forwards").setIndicator(indicator), ( 
        					tabInfo = new TabInfo("forwards", MarketListFragment.class, args)));
        	this.mapTabInfo.put(tabInfo.tag, tabInfo);
        }
        else if( buyPosition != null && buyPosition.startsWith("p") )
        {
        	String indicator = getString(R.string.market_menu_centers);
        	MarketListActivity.AddTab(this, 
        			this.mTabHost, 
        			this.mTabHost.newTabSpec("centers").setIndicator(indicator), ( 
        					tabInfo = new TabInfo("centers", MarketListFragment.class, args)));
        	this.mapTabInfo.put(tabInfo.tag, tabInfo);
        }
        else
        {
        	MarketListActivity.AddTab(this, 
        			this.mTabHost, 
        			this.mTabHost.newTabSpec("guards").setIndicator(getString(R.string.market_menu_guards)), ( 
        					tabInfo = new TabInfo("guards", MarketListFragment.class, args)));
        	this.mapTabInfo.put(tabInfo.tag, tabInfo);
        	MarketListActivity.AddTab(this, 
        			this.mTabHost, 
        			this.mTabHost.newTabSpec("forwards").setIndicator(getString(R.string.market_menu_forwards)), ( 
        					tabInfo = new TabInfo("forwards", MarketListFragment.class, args)));
        	this.mapTabInfo.put(tabInfo.tag, tabInfo);
        	MarketListActivity.AddTab(this, 
        			this.mTabHost, 
        			this.mTabHost.newTabSpec("centers").setIndicator(getString(R.string.market_menu_centers)), ( 
        					tabInfo = new TabInfo("centers", MarketListFragment.class, args)));
        	this.mapTabInfo.put(tabInfo.tag, tabInfo);
        }

        mTabHost.setOnTabChangedListener(this);
    }
    
    /**
     * Add Tab content to the Tabhost
     */
    private static void AddTab(MarketListActivity activity, TabHost tabHost, TabHost.TabSpec tabSpec, TabInfo tabInfo) 
    {
        // Attach a Tab view factory to the spec
        tabSpec.setContent(activity.new TabFactory(activity));
        tabHost.addTab(tabSpec);
    }
 
    /** (non-Javadoc)
     * @see android.widget.TabHost.OnTabChangeListener#onTabChanged(java.lang.String)
     */
    public void onTabChanged(String tag) 
    {
        //TabInfo newTab = this.mapTabInfo.get(tag);
        int pos = this.mTabHost.getCurrentTab();
        this.mViewPager.setCurrentItem(pos);
    }
 
    /* (non-Javadoc)
     * @see android.support.v4.view.ViewPager.OnPageChangeListener#onPageScrolled(int, float, int)
     */
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) 
    {
    }
 
    /* (non-Javadoc)
     * @see android.support.v4.view.ViewPager.OnPageChangeListener#onPageSelected(int)
     */
    public void onPageSelected(int position) 
    {
        this.mTabHost.setCurrentTab(position);
    }
 
    /* (non-Javadoc)
     * @see android.support.v4.view.ViewPager.OnPageChangeListener#onPageScrollStateChanged(int)
     */
    public void onPageScrollStateChanged(int state) 
    {
    }
	
	/**
	 * Show dialog for adding/removing to fav list.
	 * @param list
	 */
	public void showFavDialog(String list)
	{
		FavProgressDialogFragment newFragment = FavProgressDialogFragment.newInstance(list);
	    newFragment.show(getSupportFragmentManager(), "fav_dialog");
	}
	
	public void dissmissFavDialog()
	{
		FavProgressDialogFragment dialog = (FavProgressDialogFragment)getSupportFragmentManager().findFragmentByTag("fav_dialog");
		if( dialog != null)
			dialog.dismissAllowingStateLoss();
	}
	
	public void showBuyDialog(String idequ, String idjug, String name, boolean selectable)
	{
		BuyDialogFragment newFragment = BuyDialogFragment.newInstance(idequ, idjug, name, selectable);
		newFragment.show(getSupportFragmentManager(), "buy_dialog");
	}
	
	public void dissmissBuyDialog()
	{
		BuyDialogFragment dialog = (BuyDialogFragment)getSupportFragmentManager().findFragmentByTag("buy_dialog");
		if( dialog != null)
			dialog.dismissAllowingStateLoss();
	}
	
	public void showSortDialog(int checked) 
	{
		SortDialogFragment newFragment = SortDialogFragment.newInstance(checked);
		newFragment.show(getSupportFragmentManager(), "sort_dialog");
	}

	public void dissmissSortDialog() 
	{
		SortDialogFragment dialog = (SortDialogFragment)getSupportFragmentManager().findFragmentByTag("sort_dialog");
		if( dialog != null)
			dialog.dismissAllowingStateLoss();
	}

	public void selectSortCriteriaOrder(int item) 
	{
		int pos = this.mTabHost.getCurrentTab();
		MarketListFragment frag = (MarketListFragment)mPagerAdapter.getItem(pos);
		frag.changeSortCriteria(item);
	}
	
	@Override
	protected DrawerItem[] getDrawerItems() 
	{
		mDrawerTitles = getResources().getStringArray(R.array.drawer_titles);
		mDrawerIcons = getResources().getStringArray(R.array.drawer_icons);

		DrawerItem[] items = new DrawerItem[mDrawerTitles.length];
		for(int i=0; i<mDrawerTitles.length; i++)
		{
			int icon = getResources().getIdentifier(mDrawerIcons[i], "drawable", this.getPackageName());
			items[i] = DrawerItem.create(mDrawerTitles[i], icon);
		}

		return items;
	}

	@Override
	protected void selectItem(int position) 
	{
		setTitle(mDrawerTitles[position]);
		Log.d(TAG,"selectItem on drawer");

		switch(position) 
		{
		case 0:
			// home fragment
			Intent homeActivity = new Intent(getBaseContext(), HomeActivity.class);
			startActivity(homeActivity);
			overridePendingTransition(0,0);
			break;
		case 1:
			// private league fragment
			Intent privateLeagueActivity = new Intent(getBaseContext(), PrivateLeagueListActivity.class);
			startActivity(privateLeagueActivity);
			overridePendingTransition(0,0);
			break;
		case 2:
			// market fragment
			break;
		case 3:
			// my teams list activity
			Intent myteamsListActivity = new Intent(getBaseContext(), MyTeamsListActivity.class);
			startActivity(myteamsListActivity);
			overridePendingTransition(0,0);
			break;
		default:

			break;
		}

		mDrawerLayout.closeDrawer(mDrawerList);	
	}
}
